package com.woniuxy.commons.util;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class BeanCopyUtil {


    public static <T>T copyObject(Object source,Class<T> clazz){
        T t = null;
        try {
            t=clazz.newInstance();
            BeanUtils.copyProperties(source,t);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return t;
    }

    public static <T>List<T> copyList(List sources, Class<T> clazz){
        ArrayList<T> list = new ArrayList<T>();
        try {
            for (Object source : sources) {
                T t = clazz.newInstance();
                BeanUtils.copyProperties(source,t);
                list.add(t);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    public static <T> Page<T> copyPage(Page sources, Class<T> clazz){
        Page<T> page = new Page<>();
        ArrayList<T> records = new ArrayList<>();
        try {
            for (Object source : sources.getRecords()) {
                T t = clazz.newInstance();
                BeanUtils.copyProperties(source,t);
                records.add(t);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        page.setRecords(records);
        page.setTotal(sources.getTotal());
        page.setPages(sources.getPages());
        page.setCurrent(sources.getCurrent());
        page.setSize(sources.getSize());
        return page;
    }
}
